/**
 * Copyright © 2011 looty - Textoo
 * @link http://www.textoo.org
 * @link http://code.google.com/p/textoo/
 * @author lab9 - Bertrand Larrieu
 * @mail lab9.fr@gmail.com
 * @version 2.0
 */

package org.looty.textoo.font 
{
	import flash.text.*;
	import flash.utils.*;

	public class FontUtils 
	{
		
		static private const FONTSTYLES		:Vector.<String> = Vector.<String>([FontStyle.REGULAR, FontStyle.ITALIC, FontStyle.BOLD, FontStyle.BOLD_ITALIC]);
		
		static private const FONT_LOOK_UP	:Dictionary	 = new Dictionary();
		
		public function FontUtils() 
		{
			
		}
		
		static public function hasEmbeddedFont(textFormat:TextFormat):Boolean
		{			
			var fontStyle:String = FONTSTYLES[int(textFormat.italic) | (int(textFormat.bold) << 1)];
			
			return TextField.isFontCompatible(textFormat.font, fontStyle);
		}
		
		static public function getEmbeddedFont(textFormat:TextFormat):Font
		{
			var fontStyle:String = FONTSTYLES[int(textFormat.italic) | (int(textFormat.bold) << 1)];
			
			if (!TextField.isFontCompatible(textFormat.font, fontStyle)) return null;
			
			for each(var font:Font in Font.enumerateFonts()) if (font.fontType == FontType.EMBEDDED && font.fontName == textFormat.font && font.fontStyle == fontStyle) return font;
			
			return null;	
		}
		
		static private function getKey(textFormat:TextFormat):String
		{
			return String(textFormat.font) + "#" + String(int(textFormat.italic) | (int(textFormat.bold) << 1));
		}
		
		static public function hasGlyphs(str:String, textFormat:TextFormat):Boolean
		{
			var key:String = getKey(textFormat);
			var font:Font = FONT_LOOK_UP[key];			
			
			if (font == null) 
			{
				font = getEmbeddedFont(textFormat);
				if (font == null) return false;
				FONT_LOOK_UP[key] = font;
			}
			
			return font.hasGlyphs(str);
		}
	}

}